import { RuleOptionalStack, RuleParse } from "../type";
import globelRuleParse from "./globelRuleParse";

const groupRuleParse: RuleParse = {

	parseType: "group",

	isNested: true,

	preHandle: (parse, rule, char) => { },

	judge: (parse, rule, char) => {
		const ruleO = rule as unknown as RuleOptionalStack;
		const parseType = parse.top && parse.top.parseType;
		const ruleSt = ruleO.select;
		if (char === "(") {
			if (parseType === "switch") {
				throw new Error("字符组内不能嵌套分组");
			}
			parse.push(groupRuleParse);
			ruleO.push({ ruleType: "group" });
			return true;
		} else if (parseType === "group" && char === "!" && ruleSt !== undefined && ruleSt.children.length === 0) {
			ruleSt.info.ruleType = "catch";
			return true;
		} else if (parseType === "group" && char === "&" && ruleSt !== undefined && ruleSt.children.length === 0) {
			ruleSt.info.ruleType = "combo";
			return true;
		} else if (parseType === "group" && char === "~" && ruleSt !== undefined && ruleSt.children.length === 0) {
			ruleSt.info.ruleType = "once";
			return true;
		} else if (parseType === "group" && char === "-" && ruleSt !== undefined && ruleSt.children.length === 0) {
			ruleSt.info.ruleType = "flat";
			return true;
		} else if (char === ")") {
			if (parseType === "branch") {
				ruleO.back();
				ruleO.back();
				parse.pop();
			}
			{
				const parseType = parse.top && parse.top.parseType;
				if (parseType !== "group") {
					throw new Error("无可收尾分组项");
				}
			}
			parse.pop();
			parse.push(globelRuleParse);
			return true;
		}
		return false;
	},

	// [canNested=true]
	handle: (parse, rule, char) => { return false; },
};

export default groupRuleParse;
